(function($){
	
	$.fn.isComment = function(){

		function getFormatDateTime(time){
			
			var formatTime = null
			  , d = new Date(time)
			  , years = d.getFullYear()
			  , months = d.getMonth()+1
			  , days = d.getDate()
			  , hours = d.getHours()
			  , minutes = d.getMinutes();
			
			if(months < 10){
				months = '0' + months;
			}
			if(days < 10){
				days = '0' + days;
			}
			if(hours < 10){
				hours = '0' + hours;
			}
			if(minutes < 10){
				minutes = '0' + minutes;
			}
			
			formatTime = years+"-"+months+"-"+days+" "+hours+":"+minutes;
			
			return formatTime;
		};
		
		return $(this).each(function(){
			
			var commentForm = $('#commentForm')
			  , newComment = $('#new_comment')
			  , commentList = $('#comment_list')
			  , visitorAvatar = $('img', newComment).attr('src')
			  , visitorHomePath = $('a', newComment).attr('href')
			  , visitorNickname = $('img', newComment).attr('alt')
			  , deleteLink = $('.delete', commentList)
			  , moreReply = $('.more_reply a', commentList)
			  , moreComment = $('.more_comment a', commentList)
			  , uniqueCourseId = $('#uniqueCourseId', commentList).val();
			
			//提交一条评论
			$(commentForm).submit(function(){
				
				var commentContent = $('textarea', this);
				
				if(commentContent.val() === ''){
					commentContent.css('background','#f5cfcf');
					commentContent.animate({opacity: 0.3}, 300, function(){
						commentContent.css('background','#ffffff').css('opacity', '1');
					});
				} else{
					//TODO：验证最多140个字符
					$.ajax({
						async:false,
						url:$(this).attr('action'),
						type:'post',
						data:$(this).serialize(),
						dataType:'json',
						context:$(this),
						beforeSend: function (xhr){
							 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
						},
						statusCode:{
							403:function(){
								$('#anonymous-login').click();
							}
						},
						success:function(json){

							if(json.postTime){
								
								var newCommentContent = commentContent.val();
								
								commentContent.val('');
								
								commentList.prepend(
									['<div class="comment_item cf">',
										'<div class="fl avatar_wrap">',
											'<a href="', visitorHomePath, '" target="_blank">',
												'<img src="', visitorAvatar, '" width="40" height="40" alt="', visitorNickname,'" title="', visitorNickname, '" class=""/>',
											'</a>',
										'</div>',
										'<div class="fr comment_content_wrap content_wrap">',
											'<div class="comment_content">',
												'<input type="hidden" class="commentId" value="', json.commentId, '"/>',
												'<a href="', visitorHomePath, '" target="_blank" class="nickname">', visitorNickname, '</a>',
												'<p>', newCommentContent, '</p>',
												'<div class="reply_link">',
													'<span>', getFormatDateTime(json.postTime), '</span>',
												'</div>',
												'<a href="javascript:;" class="delete" title="删除" style="display: none;">x</a>',
											'</div>',
										'</div>',
									'</div>'].join(''));
								
								var position = $('.send', commentForm).offset();
								$('#save-pop .save-fail').hide();
								$('#save-pop .save-success').show().html(messages.commentSuccess);
								$('#save-pop').css('position','absolute')
								  			  .css('top',position.top - 8)
									  		  .css('left',position.left - 290)
									  		  .css('background','#fafafa')
									  		  .fadeIn('slow').fadeOut('slow');
							}
						},
						error:function(){
							var position = $('.send', commentForm).offset();
							$('#save-pop .save-fail').show();
							$('#save-pop .save-success').hide();
							$('#save-pop .save-success').html(messages.commentFail);
							$('#save-pop').css('position','absolute')
							  			  .css('top',position.top - 8)
								  		  .css('left',position.left - 290)
								  		  .css('background','#fafafa')
								  		  .fadeIn('slow').fadeOut('slow');
						}
					});
				}
				return false;
			});
			
			//点击回复
			$('.reply_comment, .reply_reply').live('click', function(){
				$('.new_reply').hide();
				
				var commentItem = $(this).parents('.comment_item')
				  , contentWrap = $(this).parents('.content_wrap:first')
				  , targetNickname = $('.nickname:first', contentWrap).text()
				  , newReply = $('.new_reply', commentItem);
				
				$('input[name="commentId"]', newReply).val($('.commentId', contentWrap).val());
				newReply.show();
				$('textarea', newReply).focus().val(['回复', targetNickname, '：'].join('')).focus().setCursorPosition(50);
				$('textarea', newReply).next().val(['回复', targetNickname, '：'].join(''));
				
				return false;
			});
			
			//提交一条回复
			$('.replyForm').live('submit', function(){
				
				var replyForm = $(this)
				  , replyList = $(this).parents('.reply_list')
				  , defaultValue = $('.default', replyForm)
				  , replyContent = $('textarea[name="content"]', replyForm)
				  , newReply = $('.new_reply', replyList)
				  , moreReply = $('.more_reply', replyList);
				
				if(replyContent.val() === defaultValue.val() || replyContent.val() === ''){
					replyContent.css('background','#f5cfcf');
					replyContent.animate({opacity: 0.3}, 300, function(){
						replyContent.css('background','#ffffff').css('opacity', '1');
					});
				} else{
					//TODO：验证最多140个字符
					$.ajax({
						async:false,
						url:replyForm.attr('action'),
						type:'post',
						data:replyForm.serialize(),
						dataType:'json',
						context:replyForm,
						beforeSend:function(xhr){
							xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
						},
						success:function(json){
							
							if(json.postTime){
								
								var newReplyContent = replyContent.val();
								
								newReply.hide();
								newReply.before([
									'<div class="reply_item cf">',
										'<div class="fl avatar_wrap">',
											'<a href="', visitorHomePath, '" target="_blank">',
												'<img src="', visitorAvatar, '" width="40" height="40" alt="', visitorNickname,'" title="', visitorNickname, '" class=""/>',
											'</a>',
										'</div>',
									'<div class="fr reply_content_wrap content_wrap">',
										'<input type="hidden" class="commentId" value="', json.commentId, '"/>',
										'<a href="', visitorHomePath, '" target="_blank" class="nickname">', visitorNickname, '</a>',
										'<p>', newReplyContent, '</p>',
										'<div class="reply_link">',
											'<span>', getFormatDateTime(json.postTime), '</span>',
										'</div>',
										'<a href="javascript:;" class="delete del_reply" title="删除" style="display: none;">x</a>',
									'</div>',
								'</div>'].join(''));
							}
						}
					});
				}
				return false;
			});
			
			//删除一条回复
			$('.comment_content, .reply_content_wrap').live('mouseenter', function(){
				$('.delete', $(this)).show();
			}).live('mouseleave', function(){
				$('.delete', $(this)).hide();
			});
			
			$(deleteLink).live('click', function(){

				var commentId = $(this).parent().find('.commentId').val();
				
				if(confirm('确认删除？')){

					var deleteItem = $(this).hasClass('del_reply') ? $(this).parents('.reply_item') : $(this).parents('.comment_item');
					$.ajax({
						async:false,
						url:[$.global.getContextPath(), '/comment/', commentId, '/delete'].join(''),
						type:'post',
						dataType:'json',
						context:$(this),
						beforeSend: function (xhr) {
							 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
						},
						success:function(json){
							if(json.success){
								$(deleteItem).slideUp(300, function(){
									$(this).remove();
								});
							}
						}
					});
					return false;
				}
			});
			
			//更多回复
			$(moreReply).live('click', function(){
				
				var that = $(this)
				  , moreWrap = that.parent()
				  , commentId = moreWrap.parents('.comment_content_wrap').find('.comment_content').find('.commentId').val()
				  , lastReplyId = moreWrap.prev().find('.commentId').val()
				  , deletable = that.next().val()
				  , remainReplyCount = parseInt($('span', that).text())
				  , newCommentId = that.parents().next('.reply_item').find('.commentId').val()
				  , moreReplyUrl = [$.global.getContextPath(), '/course/', uniqueCourseId, '/comment/', commentId, '/reply/more/', lastReplyId, '?del=', deletable].join('');
				
				if(newCommentId !== undefined){
					moreReplyUrl = [$.global.getContextPath(), '/course/', uniqueCourseId, '/comment/', commentId, '/reply/more/', lastReplyId, '?del=', deletable, '&newCommentId=', newCommentId].join(''); 
				}
				
				$.ajax({
					async:false,
					url:moreReplyUrl,
					type:'get',
					dataType:'html',
					context:$(this),
					beforeSend: function (xhr) {
						 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
					},
					statusCode:{
						403:function(){
							$('#anonymous-login').click();
						}
					},
					success:function(html){
						
						moreWrap.before(html);
						
						if(remainReplyCount > 10){
							$('span', that).text(remainReplyCount - 10);
						} else{
							moreWrap.remove();
						}
					}
				});
				return false;
			});
			
			//更多评论
			$(moreComment).live('click',function(){
				
				var that = $(this)
				  , moreWrap = that.parents('.more_comment')
				  , lastCommentId = moreWrap.prev().find('.comment_content').find('.commentId').val()
				  , remainCommentCount = parseInt($('span', that).text());;
				
				$.ajax({
					async:false,
					url:[$.global.getContextPath(), '/course/', uniqueCourseId, '/comment/more/', lastCommentId].join(''),
					type:'get',
					dataType:'html',
					beforeSend: function (xhr) {
						 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
					},
					success:function(html){
						
						moreWrap.before(html);
						
						if(remainCommentCount > 10){
							$('span', that).text(remainCommentCount - 10);
						} else{
							moreWrap.remove();
						}
					}
				});
				return false;
			});
		});
	};
})(jQuery);